# -*- coding: utf-8 -*-
import sys
import conf
from utils import message_dialog
from uimanager import UIManager
from ConfigParser import ConfigParser

try:
    import pygtk
    pygtk.require("2.0")
    import gtk
    import gtk.glade    
except ImportError,cause:
    sys.stderr.write("ImportError: Module is not present %s" % cause)
    sys.exit(1)

class PreferencesWindow():
    _password = None
    _userlogin = None
    
    def __init__(self):
        self.uimanager = UIManager("preferences_window")
        self.window = self.uimanager.widget("preferences_window")
        self.window.set_title("Preferências")
        
        self.userlogin_entry = self.uimanager.widget("userlogin_entry")
        self.password_entry = self.uimanager.widget("password_entry")
        
        self.window.add_button("Ok",gtk.RESPONSE_OK)
        self.window.add_button("Cancelar",gtk.RESPONSE_CANCEL)
        
        conf.create_conf_file()
        config = conf.get_config()
        
        if config.has_section("login"):
            self.userlogin_entry.set_text(config.get("login","userlogin"))
            self.password_entry.set_text(config.get("login","password"))

    def run(self):
        while True:
            response = self.window.run()
            if response == gtk.RESPONSE_OK:
                if not self._login_validate():
                    self.error_dialog()
                    continue
                break;
            elif response == gtk.RESPONSE_CANCEL:
                break;
            else:
                break;                                                
        self.window.destroy()
   
    def _login_validate(self):
        self._userlogin = self.userlogin_entry.get_text()
        self._password = self.password_entry.get_text()
        
        if len(self._userlogin) < 4 or len(self._password) < 4:
            return False

        config = conf.get_config()
        config.set("login","userlogin",self._userlogin)
        config.set("login","password",self._password)
        conf.set_config(config)
        
        return True
   
    def error_dialog(self):
        message_dialog("Não foi possível validar o usuário")

    def get_values(self):
        return (self._userlogin,self._password)
